package models

import (
	"github.com/astaxie/beego/orm"
	"github.com/satori/go.uuid"
	"time"
)

func init() {

}

type Profile struct {
	UserId    string `form:"user_id" json:"-" orm:"pk"`
	UserName  string `form:"user_name" json:"userName"`
	NickName  string `form:"nick_name" json:"nickName"`
	Slogon    string  `form:"slogon" json:"slogon"`
	Password  string `form:"password" json:"-"`
	Identicon string `form:"-" json:"identicon"`
}

func CreateProfile(userName string, nickName string, pass string) (profile Profile, err error) {

	identicon, err := Identicon()
	if err != nil {
		return Profile{}, err
	}

	userid := uuid.NewV4().String()

	o := orm.NewOrm()
	o.Begin()

	user := Profile{UserId: userid,
		UserName:  userName,
		NickName:  nickName,
		Slogon:"这是我的地盘哼哼哈哈，来来来，你来你来你来",
		Password:  pass,
		Identicon: identicon}
	_, err = o.Insert(&user)

	clientToken := ClientToken{UserId: userid,
		AccessToken:  uuid.NewV4().String(),
		TokenType:    "bearer",
		RefreshToken: uuid.NewV4().String(),
		ExpiresIn:    30 * 24 * 60 * 60,
		Scope:        "read,write",
		CreateTime:   time.Now(),
		TokenTime:    time.Now()}
	_, err = o.Insert(&clientToken)
	o.Commit()

	if err != nil {
		return Profile{}, err
	}
	return user, err
}

func GetProfile(userId string) (p Profile) {
	o := orm.NewOrm()
	profile := Profile{UserId: userId}
	o.Read(&profile, "UserId")
	return profile
}
